<template>
  <MenuItem
    :name="item.path"
    v-if="!menuHasChildren(item) && getShowMenu"
    v-bind="$props"
    :class="getLevelClass"
    :style="`color: ${getColor}`"
    @contextmenu.prevent="handleContext($event, item)"
  >
    <Icon v-if="getIcon" :icon="getIcon" :size="16" />
    <div v-if="collapsedShowTitle && getIsCollapseParent" class="mt-1 collapse-title">
      {{ getI18nName }}
    </div>
    <template #title>
      <span :class="['ml-2', `${prefixCls}-sub-title`]">
        {{ getI18nName }}
      </span>
      <SimpleMenuTag :item="item" :collapseParent="getIsCollapseParent" />
    </template>
  </MenuItem>
  <SubMenu
    :name="item.path"
    v-if="menuHasChildren(item) && getShowMenu"
    :class="[getLevelClass, theme]"
    :collapsedShowTitle="collapsedShowTitle"
    :style="`color: ${getColor}`"
    @contextmenu.prevent="handleContext($event, item)"
  >
    <template #title>
      <Icon v-if="getIcon" :icon="getIcon" :size="16" />

      <div v-if="collapsedShowTitle && getIsCollapseParent" class="mt-2 collapse-title">
        {{ getI18nName }}
      </div>

      <span v-show="getShowSubTitle" :class="['ml-2', `${prefixCls}-sub-title`]">
        {{ getI18nName }}
      </span>
      <SimpleMenuTag :item="item" :collapseParent="!!collapse && !!parent" />
    </template>
    <template v-for="childrenItem in item.children || []" :key="childrenItem.path">
      <SimpleSubMenu v-bind="$props" :item="childrenItem" :parent="false" />
    </template>
  </SubMenu>
</template>
<script lang="ts">
  import type { PropType } from 'vue';
  import type { Menu } from '/@/router/types';

  import { defineComponent, computed } from 'vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import Icon from '/@/components/Icon/index';

  import MenuItem from './components/MenuItem.vue';
  import SubMenu from './components/SubMenuItem.vue';
  import { propTypes } from '/@/utils/propTypes';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import { useContextMenu } from '/@/hooks/web/useContextMenu';
  import { CollapseContainer } from '/@/components/Container';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { it } from 'node:test';
  import { quickNavSave, findUserNav } from '/@/api/sys/quickNav';
  import { usePermissionStore } from '/@/store/modules/permission';
  const useStore = usePermissionStore();

  export default defineComponent({
    name: 'SimpleSubMenu',
    components: {
      SubMenu,
      MenuItem,
      SimpleMenuTag: createAsyncComponent(() => import('./SimpleMenuTag.vue')),
      Icon,
    },
    props: {
      item: {
        type: Object as PropType<Menu>,
        default: () => ({}),
      },
      parent: propTypes.bool,
      collapsedShowTitle: propTypes.bool,
      collapse: propTypes.bool,
      theme: propTypes.oneOf(['dark', 'light']),
    },

    setup(props) {
      const { t } = useI18n();
      const { prefixCls } = useDesign('simple-menu');

      const getShowMenu = computed(() => !props.item?.meta?.hideMenu);
      const getIcon = computed(() => props.item?.icon);
      const getColor = computed(() => props.item?.color);
      const getI18nName = computed(() => t(props.item?.name));
      const getShowSubTitle = computed(() => !props.collapse || !props.parent);
      const getIsCollapseParent = computed(() => !!props.collapse && !!props.parent);
      const getLevelClass = computed(() => {
        return [
          {
            [`${prefixCls}__parent`]: props.parent,
            [`${prefixCls}__children`]: !props.parent,
          },
        ];
      });

      function menuHasChildren(menuTreeItem: Menu): boolean {
        return (
          !menuTreeItem.meta?.hideChildrenInMenu &&
          Reflect.has(menuTreeItem, 'children') &&
          !!menuTreeItem.children &&
          menuTreeItem.children.length > 0
        );
      }

      // 鼠标右键点击事件start
      const [createContextMenu] = useContextMenu();
      const { createMessage } = useMessage();
      function handleContext(e: MouseEvent, item: Menu) {
        console.log(item.children?.length === 0, 'handleContext', e);
        let newItemName = props.item?.children?.filter((item: any) => {
          return item.name === e.srcElement.innerText;
        });

        // 如果递归调用
        if (newItemName.length !== 0 && newItemName[0]?.children.length == 0) {
          createContextMenu({
            event: e,
            items: [
              {
                // label: '添加' + e.srcElement.innerText,
                label: '添加至快捷导航',
                icon: 'ant-design:plus-outlined',
                handler: () => {
                  // 从item.children里面过滤出e.srcElement.innerText
                  let newItem = props.item.children.filter((item: any) => {
                    return item.name === e.srcElement.innerText;
                  });
                  quickNavSave({
                    menuId: newItem[0].id,
                  }).then(async (res: any) => {
                    if (res.result == 'true') {
                      createMessage.success('添加' + e.srcElement.innerText + '成功');
                      const res = await findUserNav();
                      await useStore.setQuickNavList(res.list);
                    } else {
                      createMessage.error(res.message);
                    }
                  });
                },
              },
            ],
          });
        } else if (item.children?.length === 0) {
          createContextMenu({
            event: e,
            items: [
              {
                label: '添加' + e.srcElement.innerText,
                icon: 'ant-design:plus-outlined',
                handler: () => {
                  quickNavSave({
                    menuId: props.item.id,
                  }).then(async (res: any) => {
                    if (res.result == 'true') {
                      createMessage.success('添加' + e.srcElement.innerText + '成功');
                      const res = await findUserNav();
                      await useStore.setQuickNavList(res.list);
                    } else {
                      createMessage.error(res.message);
                    }
                  });
                },
              },
            ],
          });
        }
      }
      // 鼠标右键点击事件end

      return {
        prefixCls,
        menuHasChildren,
        getShowMenu,
        getIcon,
        getColor,
        getI18nName,
        getShowSubTitle,
        getLevelClass,
        getIsCollapseParent,
        handleContext,
      };
    },
  });
</script>
